package com.test.model;

import com.test.message.Message;
import com.test.server.SyncFuture;
import com.test.server.service.impl.ServerServiceImpl;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Author mkl
 * @Date 2021/5/26 18:42
 * @Description
 */
@Slf4j
public class ConnectionManager {
    public static ConcurrentHashMap<String, Connection> connections = new ConcurrentHashMap<>();

    public static final AttributeKey<Connection> connection = AttributeKey
            .valueOf("connection");

    public static void addConnection(Connection conn) {
        connections.put(conn.getImei(), conn);
    }

    public static void removeConnection(Connection conn) {
        //判断channel
        if (conn.equals(getConnection(conn))) {
            connections.remove(conn.getImei());
        }
    }

    public static Connection getConnection(Connection conn) {
        return connections.get(conn.getImei());
    }


    public static void sendSyncMsg(SyncFuture<String> syncFuture, Message message, String imei) {
        Connection connection = Connection.getConnection(imei);
        ServerServiceImpl.futureCache.put(connection.getImei() + message.getHead() + message.getFunCode(), syncFuture);
        ChannelFuture channelFuture = connection.getChannel().writeAndFlush(message);
        //登录回复消息
        log.info("功能：{}收到设备回复消息：{}", message.getFunCode(), message);
        try {
            if (syncFuture.get(8, TimeUnit.SECONDS) != null) {
                channelFuture.addListener((ChannelFutureListener) future -> {
                    if (future.isSuccess()) {
                        log.debug("消息发送成功");
                    } else {
                        log.debug("消息发送失败");
                    }
                });
            } else {
                log.error("服务器接受命令失败");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
